# -*- encoding: utf-8 -*-
'''
@File    :   upload.py   
@Contact :   desufnocs@163.com
@des     :   文件相关接口
 
@Modify Time       @Author      @Version    @Desciption
------------      ----------    --------    -----------
2025/2/19 14:12   AssenImpact      1.0         None
'''
import os.path

import aiofiles
from fastapi import APIRouter, UploadFile, Form, HTTPException, status

from ..core.Response import success

router = APIRouter(
    prefix="/file",
    tags=["关于文件上传的接口"],
)


@router.post("/upload", summary="文件上传")
async def upload_file(file: UploadFile, path: str = Form()):
    """
    文件上传\n
    :param file:文件\n
    :param path:上传路径\n
    :return:
    """
    if len(path) == 0:
        path = os.path.join(os.path.expanduser("~"), "Downloads")
    if not os.path.exists(path):
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="路径不正确")
    path = os.path.join(path, file.filename)
    try:
        async with aiofiles.open(path, "wb") as fp:
            while content := await file.read(1024 * 1000):
                await fp.write(content)
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="文件上传失败")
    return success(msg="上传成功")
